import scrapy
from scrapy_playwright.page import PageMethod
from ..task_framework import TaskTemplate, BrowserAction, ActionType


class TemplatePlaywrightSpider(scrapy.Spider):
    """基于模板的 Playwright Spider"""

    name = 'template_playwright'

    def start_requests(self):
        # 定义任务模板
        templates = [
            self.create_infinite_scroll_task(),
            self.create_login_task(),
            self.create_form_submission_task()
        ]

        for template in templates:
            yield scrapy.Request(
                url=template.url,
                meta=template.to_playwright_meta(),
                callback=self.parse_template_result
            )

    def create_infinite_scroll_task(self) -> TaskTemplate:
        """无限滚动任务模板"""
        actions = [
            BrowserAction(ActionType.WAIT_FOR_SELECTOR, '.content', timeout=10000),
            BrowserAction(ActionType.SCROLL),
            BrowserAction(ActionType.WAIT_FOR_SELECTOR, '.new-item', timeout=5000),
            BrowserAction(ActionType.SCROLL),
        ]
        return TaskTemplate('infinite_scroll_1', 'https://example.com/scroll', actions)

    def create_login_task(self) -> TaskTemplate:
        """登录任务模板"""
        actions = [
            BrowserAction(ActionType.FILL, '#username', 'testuser'),
            BrowserAction(ActionType.FILL, '#password', 'testpass'),
            BrowserAction(ActionType.CLICK, '#login-btn'),
            BrowserAction(ActionType.WAIT_FOR_SELECTOR, '.dashboard', timeout=10000),
        ]
        return TaskTemplate('login_1', 'https://example.com/login', actions)

    def parse_template_result(self, response):
        """解析模板执行结果"""
        task_id = response.meta['task_id']

        if task_id == 'infinite_scroll_1':
            yield from self.parse_infinite_scroll(response)
        elif task_id == 'login_1':
            yield from self.parse_after_login(response)

    def parse_infinite_scroll(self, response):
        """解析无限滚动结果"""
        items = response.css('.item')
        for item in items:
            yield {
                'type': 'scroll_item',
                'content': item.css('::text').get(),
                'url': response.url
            }

    def parse_after_login(self, response):
        """解析登录后内容"""
        yield {
            'type': 'login_success',
            'dashboard_content': response.css('.dashboard ::text').get(),
            'url': response.url
        }